/// 用户服务类
/// 
/// 封装用户相关的API调用
/// 提供用户数据的增删改查功能
/// 
/// 作者: Fluttert Team
/// 日期: 2024

import '../models/user_model.dart';
import 'api_service.dart';

/// 用户服务类
/// 
/// 处理所有与用户相关的业务逻辑
class UserService {
  /// API服务实例
  final ApiService _apiService = ApiService();

  /// 获取用户列表
  /// 
  /// [page] 页码，默认为1
  /// [limit] 每页数量，默认为10
  /// 返回用户列表
  Future<List<UserModel>> getUserList({
    int page = 1,
    int limit = 10,
  }) async {
    try {
      return await _apiService.getList<UserModel>(
        '/users',
        queryParameters: {
          'page': page,
          'limit': limit,
        },
        fromJson: (json) => UserModel.fromJson(json),
      );
    } catch (e) {
      rethrow;
    }
  }

  /// 根据ID获取用户详情
  /// 
  /// [userId] 用户ID
  /// 返回用户信息
  Future<UserModel> getUserById(int userId) async {
    try {
      return await _apiService.get<UserModel>(
        '/users/$userId',
        fromJson: (json) => UserModel.fromJson(json),
      );
    } catch (e) {
      rethrow;
    }
  }

  /// 创建新用户
  /// 
  /// [name] 用户名
  /// [email] 用户邮箱
  /// [age] 用户年龄（可选）
  /// 返回创建的用户信息
  Future<UserModel> createUser({
    required String name,
    required String email,
    int? age,
  }) async {
    try {
      return await _apiService.post<UserModel>(
        '/users',
        data: {
          'name': name,
          'email': email,
          'age': age,
        },
        fromJson: (json) => UserModel.fromJson(json),
      );
    } catch (e) {
      rethrow;
    }
  }

  /// 更新用户信息
  /// 
  /// [userId] 用户ID
  /// [name] 新用户名（可选）
  /// [email] 新邮箱（可选）
  /// [age] 新年龄（可选）
  /// 返回更新后的用户信息
  Future<UserModel> updateUser({
    required int userId,
    String? name,
    String? email,
    int? age,
  }) async {
    try {
      final Map<String, dynamic> data = {};
      if (name != null) data['name'] = name;
      if (email != null) data['email'] = email;
      if (age != null) data['age'] = age;

      return await _apiService.put<UserModel>(
        '/users/$userId',
        data: data,
        fromJson: (json) => UserModel.fromJson(json),
      );
    } catch (e) {
      rethrow;
    }
  }

  /// 删除用户
  /// 
  /// [userId] 用户ID
  Future<void> deleteUser(int userId) async {
    try {
      await _apiService.delete('/users/$userId');
    } catch (e) {
      rethrow;
    }
  }
}

